<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线答题系统</title>
    <style>
        /* 全局样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f7fa;
            padding: 20px;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        /* 头部样式 */
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        /* 筛选控制区域 */
        .filter-controls {
            padding: 20px 30px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }
        
        .filter-title {
            font-weight: 600;
            font-size: 18px;
            margin-bottom: 15px;
            color: #495057;
        }
        
        .type-filters {
            display: flex;
            gap: 20px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        
        .filter-checkbox {
            display: flex;
            align-items: center;
            cursor: pointer;
            font-size: 16px;
        }
        
        .filter-checkbox input[type="checkbox"] {
            width: 18px;
            height: 18px;
            margin-right: 8px;
            cursor: pointer;
        }
        
        .filter-actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }
        
        .filter-btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .apply-filter {
            background-color: #28a745;
            color: white;
        }
        
        .apply-filter:hover {
            background-color: #218838;
            transform: translateY(-1px);
        }
        
        .shuffle-btn {
            background-color: #ffc107;
            color: #212529;
        }
        
        .shuffle-btn:hover {
            background-color: #e0a800;
            transform: translateY(-1px);
        }
        
        .filtered-count {
            margin-top: 10px;
            font-size: 14px;
            color: #6c757d;
        }
        
        /* 进度条区域 */
        .progress-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 15px 30px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }
        
        .progress-bar {
            height: 8px;
            background-color: #e9ecef;
            border-radius: 4px;
            margin: 0 30px 20px;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            width: 0%;
            transition: width 0.3s ease;
        }
        
        /* 内容区域 */
        .content {
            padding: 30px;
        }
        
        .question-card {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 25px;
            margin-bottom: 20px;
        }
        
        .question-type {
            display: inline-block;
            background-color: #667eea;
            color: white;
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 14px;
            margin-bottom: 15px;
        }
        
        .question-content {
            font-size: 18px;
            line-height: 1.8;
            margin-bottom: 20px;
            color: #495057;
        }
        
        /* 选项样式 */
        .options {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        
        .option {
            display: flex;
            align-items: flex-start;
            padding: 15px;
            background-color: white;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .option:hover {
            border-color: #667eea;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
        }
        
        .option.selected {
            border-color: #667eea;
            background-color: rgba(102, 126, 234, 0.05);
        }
        
        .option.correct {
            border-color: #28a745;
            background-color: rgba(40, 167, 69, 0.1);
        }
        
        .option.incorrect {
            border-color: #dc3545;
            background-color: rgba(220, 53, 69, 0.1);
        }
        
        /* 优化点击区域 - 自定义选择框 */
        .option .select-area {
            width: 24px;
            height: 24px;
            margin-right: 12px;
            margin-top: 3px;
            border: 2px solid #adb5bd;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            transition: all 0.2s ease;
        }
        
        /* 单选题圆形样式 */
        .option.single .select-area {
            border-radius: 50%;
        }
        
        /* 多选题方形样式 */
        .option.multiple .select-area {
            border-radius: 4px;
        }
        
        .option:hover .select-area {
            border-color: #667eea;
            transform: scale(1.1);
        }
        
        .option.selected .select-area {
            border-color: #667eea;
            background-color: #667eea;
        }
        
        .option.correct .select-area {
            border-color: #28a745;
            background-color: #28a745;
        }
        
        .option.incorrect .select-area {
            border-color: #dc3545;
            background-color: #dc3545;
        }
        
        /* 选中标记 */
        .option.selected .select-area::after,
        .option.correct .select-area::after,
        .option.incorrect .select-area::after {
            content: '✓';
            color: white;
            font-size: 16px;
            font-weight: bold;
        }
        
        .option-label {
            font-size: 16px;
            flex: 1;
        }
        
        .option-letter {
            font-weight: bold;
            color: #667eea;
            margin-right: 8px;
        }
        
        /* 按钮样式 */
        .buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 30px;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background-color: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #5a67d8;
            transform: translateY(-1px);
        }
        
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #545b62;
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        /* 题号选择器样式 */
        .question-selector {
            margin: 15px 30px;
            padding: 15px;
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
        }
        
        .selector-header {
            font-weight: 600;
            font-size: 16px;
            margin-bottom: 10px;
            color: #495057;
        }
        
        .selector-container {
            max-height: 120px;
            overflow-y: auto;
            padding: 5px;
            background-color: white;
            border: 1px solid #dee2e6;
            border-radius: 4px;
        }
        
        .question-numbers {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .question-number {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s ease;
            background-color: #f8f9fa;
            border: 2px solid #dee2e6;
        }
        
        .question-number:hover {
            background-color: #e9ecef;
            border-color: #667eea;
            transform: translateY(-1px);
        }
        
        .question-number.active {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .question-number.answered.correct {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        
        .question-number.answered.incorrect {
            background-color: #dc3545;
            color: white;
            border-color: #dc3545;
        }
        
        /* 滚动条样式 */
        .selector-container::-webkit-scrollbar {
            width: 8px;
        }
        
        .selector-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        .selector-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        .selector-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 结果显示 */
        .result {
            padding: 20px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-size: 16px;
            text-align: center;
            display: none;
        }
        
        .result.correct {
            background-color: rgba(40, 167, 69, 0.1);
            color: #28a745;
            border: 1px solid #28a745;
        }
        
        .result.incorrect {
            background-color: rgba(220, 53, 69, 0.1);
            color: #dc3545;
            border: 1px solid #dc3545;
        }
        
        .correct-answer {
            font-weight: bold;
            margin-top: 10px;
        }
        
        .explanation {
            margin-top: 15px;
            padding: 15px;
            background-color: #f8f9fa;
            border-left: 4px solid #667eea;
            border-radius: 4px;
        }
        
        /* 加载状态 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 300px;
            font-size: 18px;
            color: #667eea;
        }
        
        .loading::after {
            content: '';
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 15px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 完成页面样式 */
        .completion-page {
            text-align: center;
            padding: 50px 30px;
        }
        
        .completion-page h2 {
            font-size: 32px;
            margin-bottom: 20px;
            color: #667eea;
        }
        
        .score-display {
            font-size: 48px;
            font-weight: bold;
            margin: 30px 0;
            color: #667eea;
        }
        
        .score-details {
            font-size: 18px;
            margin-bottom: 40px;
            color: #6c757d;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                margin: 0;
                border-radius: 0;
            }
            
            .content {
                padding: 20px;
            }
            
            .question-content {
                font-size: 16px;
            }
            
            .buttons {
                flex-direction: column;
                gap: 10px;
            }
            
            .btn {
                width: 100%;
            }
            
            .filter-actions {
                flex-direction: column;
            }
            
            .filter-btn {
                width: 100%;
            }
            
            .type-filters {
                flex-direction: column;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>在线答题系统</h1>
            <p>欢迎使用自动判题功能的刷题系统</p>
        </div>
        
        <!-- 筛选控制区域 -->
        <div class="filter-controls">
            <div class="filter-title">题型筛选</div>
            <div class="type-filters" id="type-filters">
                {% for type in question_types %}
                <label class="filter-checkbox">
                    <input type="checkbox" name="question-type" value="{{ type }}" checked>
                    {{ type }}
                </label>
                {% endfor %}
            </div>
            <div class="filter-actions">
                <button class="filter-btn apply-filter" id="apply-filter-btn">应用筛选</button>
                <button class="filter-btn shuffle-btn" id="shuffle-btn">随机抽题</button>
            </div>
            <div class="filtered-count" id="filtered-count">显示全部 {{ total_questions }} 题</div>
        </div>
        
        <div class="progress-info">
            <span><strong>当前题号:</strong> <span id="current-question">{{ current_question }}</span></span>
            <span><strong>得分:</strong> <span id="score">0</span></span>
        </div>
        
        <!-- 题号选择器 -->
        <div class="question-selector">
            <div class="selector-header">题目导航</div>
            <div class="selector-container">
                <div class="question-numbers" id="question-numbers"></div>
            </div>
        </div>
        
        <div class="content">
            <div id="question-area">
                <div class="loading">正在加载题目</div>
            </div>
            
            <div class="buttons">
                <button id="prev-btn" class="btn btn-secondary" disabled>上一题</button>
                <button id="submit-btn" class="btn btn-primary">提交答案</button>
                <button id="next-btn" class="btn btn-primary" disabled>下一题</button>
            </div>
        </div>
    </div>
    
    <script>
        // 获取DOM元素
        const questionArea = document.getElementById('question-area');
        const currentQuestionEl = document.getElementById('current-question');
        const scoreEl = document.getElementById('score');
        const submitBtn = document.getElementById('submit-btn');
        const nextBtn = document.getElementById('next-btn');
        const prevBtn = document.getElementById('prev-btn');
        const filteredCountEl = document.getElementById('filtered-count');
        const questionNumbersEl = document.getElementById('question-numbers');
        
        // 全局变量
        let currentQuestionId = {{ current_question }};
        let totalQuestions = {{ total_questions }};
        let currentIndex = {{ current_question }}; // 当前题号
        let isAnswered = false;
        let userAnswers = {}; // 存储用户当前问题的答案
        
        // 下一题 - 调用后端API获取下一题
        function goToNextQuestion() {
            fetch('/next')
                .then(response => response.json())
                .then(data => {
                    if (data.next_question) {
                        currentQuestionId = data.next_question;
                        currentIndex = data.current_index;
                        totalQuestions = data.total_questions;
                        loadQuestion(currentQuestionId);
                        updateProgress();
                        updateQuestionSelector(currentIndex);
                        submitBtn.disabled = false;
                        updateButtonStates(data.has_prev || false, data.has_next || false);
                    } else {
                        // 完成所有题目
                        showCompletionPage(data.final_score);
                    }
                })
                .catch(error => {
                    console.error('加载下一题出错:', error);
                    alert('加载下一题失败，请刷新页面重试');
                });
        }
        
        // 初始化题号选择器
        function initQuestionSelector() {
            questionNumbersEl.innerHTML = '';
            for (let i = 1; i <= totalQuestions; i++) {
                const numberBtn = document.createElement('div');
                numberBtn.className = 'question-number';
                numberBtn.textContent = i;
                numberBtn.dataset.number = i;
                
                // 初始状态
                if (i === currentIndex) {
                    numberBtn.classList.add('active');
                }
                
                // 添加点击事件
                numberBtn.addEventListener('click', function() {
                    const questionNumber = parseInt(this.dataset.number);
                    goToQuestionByNumber(questionNumber);
                });
                
                questionNumbersEl.appendChild(numberBtn);
            }
        }
        
        // 更新题号选择器状态
        function updateQuestionSelector(activeNumber) {
            document.querySelectorAll('.question-number').forEach(btn => {
                btn.classList.remove('active');
                if (parseInt(btn.dataset.number) === activeNumber) {
                    btn.classList.add('active');
                }
            });
        }
        
        // 跳转到指定题号
        function goToQuestionByNumber(questionNumber) {
            fetch(`/goto/${questionNumber}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应错误');
                }
                return response.json();
            })
            .then(data => {
                if (data.question_id) {
                    currentQuestionId = data.question_id;
                    currentIndex = data.current_index;
                    totalQuestions = data.total_questions;
                    loadQuestion(currentQuestionId);
                    updateProgress();
                    updateQuestionSelector(currentIndex);
                    updateButtonStates(data.has_prev || false, data.has_next || false);
                }
            })
            .catch(error => {
                console.error('跳转到指定题号出错:', error);
                alert('跳转失败，请刷新页面重试');
            });
        }
        
        // 更新进度条
        function updateProgress() {
            // 只更新题号显示
            currentQuestionEl.textContent = currentQuestionId;
        }
        
        // 加载题目
        function loadQuestion(questionId) {
            questionArea.innerHTML = '<div class="loading">正在加载题目</div>';
            isAnswered = false;
            userAnswers = {};
            
            fetch(`/question/${questionId}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(question => {
                    renderQuestion(question);
                    // 初始状态：如果当前不是第一题，则启用上一题按钮
                    const hasPrev = currentIndex > 1;
                    updateButtonStates(hasPrev);
                })
                .catch(error => {
                    console.error('加载题目时出错:', error);
                    questionArea.innerHTML = `<div style="text-align: center; padding: 50px; color: #dc3545;">加载题目失败，请刷新页面重试</div>`;
                });
        }
        
        // 渲染题目 - 优化后的答案点击逻辑
        function renderQuestion(question) {
            let optionsHtml = '';
            const isMultipleChoice = question.type === '多选题';
            const optionClass = isMultipleChoice ? 'multiple' : 'single';
            
            for (const [letter, text] of Object.entries(question.options)) {
                optionsHtml += `
                <div class="option ${optionClass}" data-value="${letter}">
                    <div class="select-area"></div>
                    <label class="option-label">
                        <span class="option-letter">${letter}.</span>
                        ${text}
                    </label>
                </div>
                `;
            }
            
            questionArea.innerHTML = `
            <div class="question-card">
                <div class="question-type">${question.type}</div>
                <div class="question-content">${question.content}</div>
                
                <div id="result-area" class="result"></div>
                
                <div class="options" id="options-container">
                    ${optionsHtml}
                </div>
                
                <div id="explanation-area" class="explanation"></div>
            </div>
            `;
            
            // 添加选项点击事件 - 优化为鼠标悬停即可点击
            document.querySelectorAll('.option').forEach(option => {
                // 点击整个选项区域
                option.addEventListener('click', function() {
                    if (isAnswered) return;
                    
                    const letter = this.getAttribute('data-value');
                    
                    if (isMultipleChoice) {
                        // 多选逻辑
                        if (userAnswers[letter]) {
                            delete userAnswers[letter];
                            this.classList.remove('selected');
                        } else {
                            userAnswers[letter] = true;
                            this.classList.add('selected');
                        }
                    } else {
                        // 单选逻辑
                        // 移除所有选项的选中状态
                        document.querySelectorAll('.option').forEach(opt => {
                            opt.classList.remove('selected');
                        });
                        // 添加当前选项的选中状态
                        this.classList.add('selected');
                        userAnswers = { [letter]: true };
                    }
                });
            });
        }
        
        // 获取用户选择的答案
        function getUserAnswer() {
            const answer = Object.keys(userAnswers).sort();
            return answer.length > 0 ? answer : null;
        }
        
        // 提交答案
        function submitAnswer() {
            // 获取当前问题ID
            const questionId = currentQuestionId;
            
            // 获取用户答案
            const userAnswer = getUserAnswer();
            
            // 检查是否有选择答案
            if (!userAnswer) {
                alert('请选择答案后再提交');
                return;
            }
            
            // 发送答案到服务器
            fetch('/submit_answer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    question_id: questionId,
                    answer: userAnswer
                })
            })
            .then(response => response.json())
            .then(data => {
                // 更新得分
                scoreEl.textContent = data.score;
                
                // 获取问题信息用于显示结果
                fetch(`/question/${questionId}`)
                    .then(response => response.json())
                    .then(question => {
                        // 显示结果
                        showResult(data, question);
                    });
                
                // 设置已回答状态
                isAnswered = true;
                
                // 更新按钮状态
                submitBtn.disabled = true;
                nextBtn.disabled = false;
            });
        }
        
        // 显示答题结果
        function showResult(data, question) {
            const resultArea = document.getElementById('result-area');
            const explanationArea = document.getElementById('explanation-area');
            
            // 显示结果区域
            resultArea.className = `result ${data.correct ? 'correct' : 'incorrect'}`;
            resultArea.innerHTML = `
                <strong>${data.correct ? '回答正确！' : '回答错误！'}</strong>
                <div class="correct-answer">正确答案: ${data.correct_answer}</div>
            `;
            resultArea.style.display = 'block';
            
            // 高亮显示正确和错误的选项
            document.querySelectorAll('.option').forEach(option => {
                const letter = option.getAttribute('data-value');
                
                // 移除之前的高亮
                option.classList.remove('selected');
                
                // 标记正确答案
                if (data.correct_answer.includes(letter)) {
                    option.classList.add('correct');
                }
                
                // 标记用户错误选择
                if (userAnswers[letter] && !data.correct_answer.includes(letter)) {
                    option.classList.add('incorrect');
                }
                
                // 禁用选项点击
                option.style.cursor = 'default';
            });
            
            // 显示解释（如果有）
            if (data.explanation) {
                explanationArea.textContent = `解释: ${data.explanation}`;
                explanationArea.style.display = 'block';
            } else {
                explanationArea.style.display = 'none';
            }
        }
        
        // 更新按钮状态
        function updateButtonStates(hasPrev = false, hasNext = false) {
            prevBtn.disabled = !hasPrev;
            
            if (isAnswered) {
                submitBtn.disabled = true;
                nextBtn.disabled = !hasNext;
            } else {
                submitBtn.disabled = false;
                nextBtn.disabled = true;
            }
        }
        
        // 下一题 - 调用后端API获取下一题
        function goToNextQuestion() {
            fetch('/next')
                .then(response => response.json())
                .then(data => {
                    if (data.next_question) {
                        currentQuestionId = data.next_question;
                        currentIndex = data.current_index;
                        totalQuestions = data.total_questions;
                        loadQuestion(currentQuestionId);
                        updateProgress();
                        submitBtn.disabled = false;
                        updateButtonStates(data.has_prev || false, data.has_next || false);
                    } else {
                        // 完成所有题目
                        showCompletionPage(data.final_score);
                    }
                })
                .catch(error => {
                    console.error('加载下一题出错:', error);
                    alert('加载下一题失败，请刷新页面重试');
                });
        }
        
        // 上一题 - 调用后端API获取上一题
        function goToPreviousQuestion() {
            fetch('/previous')
                .then(response => response.json())
                .then(data => {
                    if (data.previous_question) {
                        currentQuestionId = data.previous_question;
                        currentIndex = data.current_index;
                        totalQuestions = data.total_questions;
                        loadQuestion(currentQuestionId);
                        updateProgress();
                        updateQuestionSelector(currentIndex);
                        submitBtn.disabled = false;
                        updateButtonStates(data.has_prev || false, data.has_next || false);
                    }
                })
                .catch(error => {
                    console.error('加载上一题出错:', error);
                    alert('加载上一题失败，请刷新页面重试');
                });
        }
        
        // 绑定按钮事件
        prevBtn.addEventListener('click', goToPreviousQuestion);
        nextBtn.addEventListener('click', goToNextQuestion);
        submitBtn.addEventListener('click', submitAnswer);
        
        // 初始化
        initQuestionSelector();
        
        // 显示完成页面
        function showCompletionPage(finalScore) {
            const score = finalScore || scoreEl.textContent;
            
            questionArea.innerHTML = `
            <div class="completion-page">
                <h2>恭喜您完成了所有题目！</h2>
                <div class="score-display">${score}/${totalQuestions}</div>
                <div class="score-details">
                    <p>您的得分率: ${Math.round((score / totalQuestions) * 100)}%</p>
                    <p>总共回答了 ${totalQuestions} 道题目，其中答对了 ${score} 道。</p>
                </div>
                <button onclick="window.location.reload()" class="btn btn-primary">重新开始</button>
            </div>
            `;
            
            // 隐藏按钮
            submitBtn.style.display = 'none';
            nextBtn.style.display = 'none';
            prevBtn.style.display = 'none';
        }
        
        // 应用筛选
        document.getElementById('apply-filter-btn').addEventListener('click', function() {
            const selectedTypes = Array.from(document.querySelectorAll('input[name="question-type"]:checked'))
                .map(cb => cb.value);
            
            fetch('/set_filter', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    types: selectedTypes
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.has_questions) {
                    totalQuestions = data.filtered_count;
                    filteredCountEl.textContent = `显示 ${data.filtered_count} 题`;
                    updateProgress();
                    
                    // 重置并加载第一题
                    fetch('/next')
                        .then(response => response.json())
                        .then(nextData => {
                            if (nextData.next_question) {
                                currentQuestionId = nextData.next_question;
                                currentIndex = nextData.current_index;
                                loadQuestion(currentQuestionId);
                                scoreEl.textContent = '0';
                            }
                        });
                } else {
                    alert('没有符合条件的题目，请选择其他题型。');
                }
            })
            .catch(error => {
                console.error('应用筛选出错:', error);
                alert('应用筛选失败，请刷新页面重试');
            });
        });
        
        // 随机抽题
        document.getElementById('shuffle-btn').addEventListener('click', function() {
            fetch('/shuffle_questions')
                .then(response => response.json())
                .then(data => {
                    if (data.shuffled) {
                        totalQuestions = data.total_questions;
                        filteredCountEl.textContent = `显示 ${data.total_questions} 题`;
                        updateProgress();
                        
                        // 重置并加载第一题
                        fetch('/next')
                            .then(response => response.json())
                            .then(nextData => {
                                if (nextData.next_question) {
                                    currentQuestionId = nextData.next_question;
                                    currentIndex = nextData.current_index;
                                    loadQuestion(currentQuestionId);
                                    scoreEl.textContent = '0';
                                }
                            });
                    }
                })
                .catch(error => {
                    console.error('随机抽题出错:', error);
                    alert('随机抽题失败，请刷新页面重试');
                });
        });
        
        // 事件监听器
        submitBtn.addEventListener('click', submitAnswer);
        nextBtn.addEventListener('click', goToNextQuestion);
        prevBtn.addEventListener('click', function() {
            alert('上一题功能暂不可用，当前已启用随机抽题模式');
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', function(event) {
            if (event.key === 'ArrowRight' && !nextBtn.disabled) {
                goToNextQuestion();
            } else if (event.key === 'Enter' && !submitBtn.disabled) {
                submitAnswer();
            }
            // Ctrl+A 全选筛选框
            if (event.ctrlKey && event.key === 'a' && event.target.closest('.type-filters')) {
                const checkboxes = document.querySelectorAll('input[name="question-type"]');
                const allChecked = Array.from(checkboxes).every(cb => cb.checked);
                checkboxes.forEach(cb => {
                    cb.checked = !allChecked;
                });
                event.preventDefault();
            }
        });
        
        // 初始化
        updateProgress();
        if (totalQuestions > 0) {
            loadQuestion(currentQuestionId);
        } else {
            questionArea.innerHTML = '<div style="text-align: center; padding: 50px; color: #dc3545;">没有找到题目数据</div>';
        }
    </script>
</body>
</html>